<template>
  <view class="main">
    <view class="address">
      <view class="address-icons">
        <uni-icons type="location" color="#2979ff" size="25"></uni-icons>
        <view class="dotted-line"></view>
        <uni-icons type="location-filled" color="#2979ff" size="25"></uni-icons>
      </view>
      <view class="address-content">
        <view class="user-address">
          <div
            class="address-section"
            v-if="letterOrder.fromAddressId != '0'"
            @click="
              switchPage(
                '/pages/address/address-edit?id=' + letterOrder.fromAddressId
              )
            "
          >
            <text class="user-info">
              {{ fromAddress.name + " " + fromAddress.phoneNumber }}
            </text>
            <text class="address-info">
              {{ fromAddress.address }}
            </text>
          </div>
          <input
            v-else
            v-on:click="switchPage('/pages/address/address?type=from')"
            disabled
            placeholder="请选择我的地址"
            class="address-section"
          />
          <text
            class="address-book"
            v-on:click="switchPage('/pages/address/address?type=from')"
            >地址簿</text
          >
        </view>
        <view class="user-address">
          <div
            class="address-section"
            v-if="letterOrder.toAddressId != '0'"
            @click="
              switchPage('/pages/address/address-edit?id=' + toAddress.id)
            "
          >
            <text class="user-info">
              {{ toAddress.name + " " + toAddress.phoneNumber }}
            </text>
            <text class="address-info">
              {{ toAddress.address }}
            </text>
          </div>
          <input
            v-else
            disabled
            v-on:click="switchPage('/pages/address/address?type=to')"
            placeholder="请选择目标地址"
            class="address-section"
          />
          <text
            class="address-book"
            v-on:click="switchPage('/pages/address/address?type=to')"
            >地址簿</text
          >
        </view>
      </view>
    </view>
    <uni-forms ref="form" :modelValue="letterOrder">
      <uni-forms-item label="信件类型">
        <view>
          <uni-data-checkbox
            v-model="lettetType"
            :localdata="[
              { value: 0, text: '普通信件' },
              { value: 1, text: '手写信件' },
            ]"
          ></uni-data-checkbox>
        </view>
      </uni-forms-item>
      <template v-if="lettetType == 0">
        <uni-forms-item name="wordCount" label="字数">
          <uni-data-picker
            v-if="wordUnitList.length > 0"
            :inputBorder="false"
            v-model="letterOrder.postPictureOrder.wordUnitId"
            :localdata="computeWordUnit"
            :map="pickerMap"
            popup-title="请选择字数"
            placeholder="请选择字数"
            @change="wordChange"
          ></uni-data-picker>
        </uni-forms-item>
        <uni-forms-item name="wordContet" label="内容">
          <uni-easyinput
            type="textarea"
            autoHeight
            :maxlength="wordLimit"
            :inputBorder="false"
            v-model="letterOrder.postPictureOrder.wordContent"
            placeholder="请输入详细内容"
          ></uni-easyinput>
          <div>
            {{ letterOrder.postPictureOrder.wordContent.length }}/{{
              wordLimit
            }}
          </div>
        </uni-forms-item>
      </template>
      <template v-else>
        <uni-forms-item label="手写照片数量">
          <uni-data-picker
            v-if="writeUnitList.length > 0"
            :inputBorder="false"
            v-model="letterOrder.postPictureOrder.writeUnitId"
            :localdata="computeWriteUnit"
            :map="pickerMap"
            popup-title="请选择手写信照片数量"
            placeholder="请选择手写信照片数量"
            @change="writeChange"
          ></uni-data-picker>
        </uni-forms-item>
        <uni-forms-item label="手写照片" class="form-item">
          <uploaderVue ref="writeUploader" :limit="writeLimit"></uploaderVue>
        </uni-forms-item>
      </template>
      <uni-forms-item label="照片数量">
        <uni-data-picker
          v-if="photoUnitList.length > 0"
          :inputBorder="false"
          v-model="letterOrder.postPictureOrder.pictureUnitId"
          :localdata="computePhotoUnit"
          :map="pickerMap"
          popup-title="请选择照片数量"
          placeholder="请选择照片数量"
          @change="photoChange"
        ></uni-data-picker>
      </uni-forms-item>
      <uni-forms-item label="照片" class="form-item">
        <uploaderVue ref="photoUploader" :limit="photoLimit"></uploaderVue>
      </uni-forms-item>
      <uni-forms-item label="信纸样式" class="form-item">
        <image
          class="template-cover"
          mode="aspectFix"
          :src="letterOrder.postPictureOrder.templatePicture"
          v-if="letterOrder.postPictureOrder.templatePicture"
        ></image>
        <div class="info" @click="switchPage('/pages/template/template')">
          <div class="placeholder">
            {{
              letterOrder.postPictureOrder.templateId
                ? "重新选择样式"
                : "请选择信纸样式"
            }}
          </div>
          <image
            style="width: 50rpx; opacity: 0.2"
            src="@/static/icons/right.png"
            mode="widthFix"
          ></image>
        </div>
      </uni-forms-item>
      <uni-forms-item label="快递" v-if="version == 0">
        <uni-data-picker
          :inputBorder="false"
          v-model="letterOrder.deliveryId"
          :localdata="computeDelivery"
          :map="{ text: 'name', value: 'id' }"
          popup-title="请选择快递"
          placeholder="请选择快递"
        ></uni-data-picker>
      </uni-forms-item>

      <uni-forms-item label="商品" class="form-item">
        <div class="products" v-if="letterOrder.postPictureOrder.orderProducts">
          <div
            class="product"
            v-for="(orderProduct, index) in letterOrder.postPictureOrder
              .orderProducts"
            :key="index"
          >
            {{ orderProduct.product.name + " x" + orderProduct.count }}
          </div>
        </div>
        <div class="info" @click="switchPage('/pages/product/product-list')">
          <div class="placeholder">
            {{ "可以选择随寄商品" }}
          </div>
          <image
            style="width: 50rpx; opacity: 0.2"
            src="@/static/icons/right.png"
            mode="widthFix"
          ></image>
        </div>
      </uni-forms-item>
    </uni-forms>
    <button plain="true" class="submit" @click="submit">提交</button></view
  >
</template>
<script lang="ts">
import {
  Address,
  Delivery,
  Order,
  OrderProduct,
  Product,
  searchVO,
  Template,
  UnitPrice,
} from "@/typings";
import uploaderVue from "@/components/uploader/uploader.vue";
import { listUnit } from "@/api/unit";
import Vue from "vue";
import { createOrder, ORDER_TYPE_LETTER } from "@/api/order";
import { listDelivery } from "@/api/delivery";
import { mapState } from "vuex";
export default Vue.extend({
  components: { uploaderVue },
  computed: {
    ...mapState("setting", ["version"]),
    computePhotoUnit() {
      let list: UnitPrice[] = this.photoUnitList.map((res) => {
        if (res.description) {
          res.description = `${res.first}张照片 ￥${res.firstPrice}元 (${res.description})`;
        } else {
          res.description = `${res.first}张照片 ￥${res.firstPrice}元 `;
        }
        if (res.renewalPrice > 0) {
          res.first = 99;
        }
        return res;
      });
      return list;
    },
    computeWriteUnit() {
      let list: UnitPrice[] = this.writeUnitList.map((res) => {
        if (res.description) {
          res.description = `${res.first}张照片 ￥${res.firstPrice}元 (${res.description})`;
        } else {
          res.description = `${res.first}张照片 ￥${res.firstPrice}元 `;
        }
        if (res.renewalPrice > 0) {
          res.first = 99;
        }
        return res;
      });
      return list;
    },
    computeWordUnit() {
      let list: UnitPrice[] = this.wordUnitList.map((res) => {
        if (res.description) {
          res.description = `${res.first}字 ￥${res.firstPrice}元 (${res.description})`;
        } else {
          res.description = `${res.first}字 ￥${res.firstPrice}元 `;
        }
        if (res.renewalPrice > 0) {
          res.first = 9999999;
        }
        return res;
      });
      return list;
    },
    computeDelivery() {
      let list: Delivery[] = this.deliveryList.map((res) => {
        res.name = res.name + " ￥" + res.price + "元";
        return res;
      });
      return list;
    },
  },
  data: () => {
    return {
      letterOrder: {
        finalPrice: 0,
        couponPrice: 0,
        originPrice: 0,
        orderStatus: 0,
        deliveryId: "0",
        delivery: {} as Delivery,
        fromAddressId: "0",
        toAddressId: "0",
        type: ORDER_TYPE_LETTER,
        postPictureOrder: {
          pictureUnitId: "0",
          pictureUrls: "",
          picturePrice: 0,
          wordUnitId: "0",
          wordContent: "",
          wordPrice: 0,
          writeUnitId: "0",
          writePictureUrls: "",
          templateId: "0",
          templatePicture: "",
          templatePrice: 0,
          orderProducts: [] as OrderProduct[],
        },
      },
      wordUnitList: [] as UnitPrice[],
      photoUnitList: [] as UnitPrice[],
      writeUnitList: [] as UnitPrice[],
      deliveryList: [] as Delivery[],
      pickerMap: { text: "description", value: "id" },
      photoSearchVO: {
        type: "照片",
        pageNum: 1,
        pageSize: 100,
      } as searchVO,
      wordSearchVO: {
        type: "字数",
        pageNum: 1,
        pageSize: 100,
      } as searchVO,
      writeSearchVO: {
        type: "手写",
        pageNum: 1,
        pageSize: 100,
      } as searchVO,
      deliverySearchVO: {
        pageNum: 1,
        pageSize: 100,
      },
      photoLimit: 0,
      wordLimit: 1,
      writeLimit: 0,
      // 手写信还是普通信
      lettetType: 0,
      toAddress: {} as Address,
      fromAddress: {} as Address,
    };
  },
  onLoad() {
    this.listPhotoUnit();
    this.listWordUnit();
    this.listWriteUnit();
    this.listDelivery();
  },
  methods: {
    submit() {
      if (this.letterOrder.postPictureOrder.pictureUnitId == "0") {
        uni.showToast({ title: "请选择照片数量", icon: "error" });
        return;
      }
      let photoUploader = this.$refs.photoUploader as any;
      let photoFiles = photoUploader.getUploadFiles();
      if (photoFiles.length != photoUploader.files.length) {
        uni.showToast({
          title: "有未上传照片",
          icon: "error",
        });
        return;
      }
      this.letterOrder.postPictureOrder.pictureUrls =
        JSON.stringify(photoFiles);
      // 手写信件或者普通信件
      if (this.lettetType == 1) {
        if (this.letterOrder.postPictureOrder.writeUnitId == "0") {
          uni.showToast({ title: "请选择手写照片数量", icon: "error" });
          return;
        }
        let writeUploader = this.$refs.writeUploader as any;
        let writeFiles = writeUploader.getUploadFiles();
        if (writeFiles.length != writeUploader.files.length) {
          uni.showToast({
            title: "有未上传手写信图片",
            icon: "error",
          });
          return;
        }
        this.letterOrder.postPictureOrder.writePictureUrls =
          JSON.stringify(writeFiles);
        this.letterOrder.postPictureOrder.wordContent = "";
        this.letterOrder.postPictureOrder.wordUnitId = "";
      } else if (this.lettetType == 0) {
        if (this.letterOrder.postPictureOrder.wordUnitId == "0") {
          uni.showToast({ title: "请选择字数", icon: "error" });
          return;
        }
        this.letterOrder.postPictureOrder.writeUnitId = "";
        this.letterOrder.postPictureOrder.writePictureUrls = "";
      }
      createOrder(this.letterOrder).then((res: Order) => {
        if (res.id) {
          this.switchPage("/pages/order/order-details?id=" + res.id);
        }
      });
    },
    switchPage(url: string) {
      uni.navigateTo({
        url,
        events: {
          templateSelect: (res: Template) => {
            this.letterOrder.postPictureOrder.templatePicture = res.picture;
            this.letterOrder.postPictureOrder.templateId = res.id;
          },
          addressSelect: (res: Address) => {
            if (res.type == "to") {
              this.toAddress = res;
              this.letterOrder.toAddressId = res.id;
            } else {
              this.fromAddress = res;
              this.letterOrder.fromAddressId = res.id;
            }
          },
          productsSelect: (res: Product[]) => {
            let orderProduct: OrderProduct[] = [];
            res.forEach((prod) => {
              orderProduct.push({
                productId: prod.id,
                product: prod,
                count: prod.count,
              });
            });
            this.letterOrder.postPictureOrder.orderProducts = orderProduct;
          },
        },
      });
    },
    listPhotoUnit() {
      listUnit(this.photoSearchVO).then((res) => {
        this.photoUnitList.push(...res.list);
      });
    },
    listWordUnit() {
      listUnit(this.wordSearchVO).then((res) => {
        this.wordUnitList.push(...res.list);
      });
    },
    listWriteUnit() {
      listUnit(this.writeSearchVO).then((res) => {
        this.writeUnitList.push(...res.list);
      });
    },
    listDelivery() {
      listDelivery(this.deliverySearchVO).then((res) => {
        this.deliveryList.push(...res.list);
      });
    },
    writeChange({ detail }) {
      let value = detail.value[0];
      this.writeUnitList.forEach((res) => {
        if (value.value == res.id) {
          this.writeLimit = res.first;
        }
      });
    },
    photoChange({ detail }) {
      let value = detail.value[0];
      this.photoUnitList.forEach((res) => {
        if (value.value == res.id) {
          this.photoLimit = res.first;
        }
      });
    },
    wordChange({ detail }) {
      let value = detail.value[0];
      this.wordUnitList.forEach((res) => {
        if (value.value == res.id) {
          this.wordLimit = res.first;
        }
      });
    },
  },
});
</script>
<style lang="scss" scoped>
.main {
  border-radius: 15rpx;
  margin: 0 20rpx;
  padding: 20rpx;

  .address {
    background-color: white;
    display: flex;
    align-items: center;
    .address-icons {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 0 20rpx 0 0rpx;
      // margin-top: 25.83rpx;

      .dotted-line {
        margin: 8.83rpx 0 8.83rpx 0;
        height: 50rpx;
        width: 1rpx;
        border-right: 4rpx dashed #e3e3e3;
      }
    }

    .address-content {
      display: flex;
      flex-direction: column;
      flex: 2;

      .address-book {
        padding: 0 17.66rpx 0 17.66rpx;
        border-left: 1px solid #e3e3e3;
      }

      .user-address {
        display: flex;
        border-bottom: 1px solid #e3e3e3;
        padding: 26.5rpx 0 26.5rpx 0;
        align-items: center;

        .address-section {
          display: flex;
          flex-direction: column;
          flex: 2;
          .user-info {
            font-size: 35rpx;
            font-weight: bold;
          }

          .address-info {
            color: #7b7b7f;
          }
        }
      }

      .target-address {
        display: flex;
        align-items: center;
        padding: 26.5rpx 0 26.5rpx 0;

        .address-section {
          flex: 2;
        }
      }
    }
  }
  .submit {
    width: 300rpx;
    height: 80rpx;
    line-height: 80rpx;
    border-radius: 40rpx;
    margin-top: 50rpx;
    margin-bottom: 30rpx;
    border: 0;
    color: white;
    box-shadow: 10rpx 10rpx 15rpx rgb(245, 245, 245);
    background-color: rgb(0, 170, 255);
  }
  .info {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .placeholder {
      line-height: 38px;
      color: rgba($color: #000000, $alpha: 0.5);
    }
  }
  .template-cover {
    width: 100rpx;
    height: 100rpx;
  }
}
</style>
